<template>
  <div class="container">
    <van-nav-bar title="巡检检验录入" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <div class="publicBox formStyle">
      <van-row type="flex" justify="end" style="margin-bottom:10px;">
        <van-button style="margin-right:5px;" size="small" type="info" native-type="submit" :disabled="!ruleForm.planBatchNo" @click="defectiveModel = true">不良品登记</van-button>
        <van-button style="width:80px" size="small" type="info" native-type="submit" :disabled="!ruleForm.planBatchNo" @click="submitForm">提 交</van-button>
      </van-row>
      <van-cell-group style="margin-bottom:5px;">
        <van-field v-model="planBatchNo" label="工单批次号" placeholder="请扫描工单批次码" right-icon="scan" @click-right-icon="scan" @keyup.enter.native="getDataByPlanBatchNo(planBatchNo)" />
      </van-cell-group>
      <div v-if="isShowForm" class="inputBox">
        <div style="margin-bottom:5px;">
          <van-form class="vanForm" label-width="60px" label-align="left">
            <van-collapse v-model="activeNames">
              <van-collapse-item name="1">
                <template #title>
                  <div>工单批次号 <span style="margin-left:20px;">{{ ruleForm.planBatchNo }}</span></div>
                </template>
                <van-row>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.proLineName" readonly label="产线" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.procedureName" class="mustInput" readonly label="工序" placeholder="请选择工序" @focus="showProcedure = true" />
                  </van-col>

                  <van-col :span="12">
                    <van-field v-model="ruleForm.factoryName" class="mustInput" label="工位" readonly placeholder="请选择工位" 
                    @focus="showFactory = true" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.patrolCheckNum" label="检验数量" type="digit" readonly />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.equName" label="设备" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.qualifiedNum" type="digit" class="mustInput" label="合格数" placeholder="请输入合格数" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.badNum" label="不良数" class="mustInput" type="digit" readonly placeholder="请输入不良数" @focus="defectiveModel = true" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.patrolCheckName" label="检验人" class="mustInput" @focus="showUser = true" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.scrapNum" label="报废数" type="digit" class="mustInput" readonly placeholder="请输入报废数" @focus="defectiveModel = true" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.remarks" rows="1" autosize label="备注" class="mustInput" type="textarea" placeholder="请输入备注" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.patrolCheckAt" label="检验时间" class="mustInput" @focus="showTime = true" />
                  </van-col>
                  <van-col :span="24">
                    <van-field name="uploader" label="文件上传" class="mustInput">
                      <template #input>
                        <van-uploader v-model="ruleForm.fileList" multiple :max-count="5" :after-read="afterRead()" :max-size="5242880" accept="image/jpeg ,image/png" @oversize="onOversize" />
                      </template>
                    </van-field>
                  </van-col>
                </van-row>
              </van-collapse-item>

            </van-collapse>
          </van-form>
        </div>
        <div class="qualityContent">
          <h1>质量控点</h1>
          <div class="contentItem">
            <!-- 质量控点 -->
            <quality-control ref="qualityControl" :item-list.sync="ruleForm.itemList" />
          </div>
        </div>
      </div>
    </div>
    <!--  工序选择 -->
    <van-popup v-model="showProcedure" position="bottom" :style="{ height: '30%' }">
      <van-picker show-toolbar :columns="procedureList.map(item=>item.procedureName).filter(item=>!procedureFilterText || item.toLowerCase().includes(procedureFilterText.toLowerCase()))" @confirm="selectProcedure" @cancel="showProcedure = false">
        <template slot="title">
          <van-search v-model="procedureFilterText" style="width:70%" placeholder="请输入工序名称" @clear=" procedureFilterText = ''" />
        </template>
      </van-picker>
    </van-popup>
    <!--  工位选择 -->
    <van-popup v-model="showFactory" position="bottom" :style="{ height: '30%' }">
      <van-picker show-toolbar :columns="factoryList.map(item=>item.factoryName).filter(item=>!factoryFilterText || item.toLowerCase().includes(factoryFilterText.toLowerCase()))" @confirm="selectFactory" @cancel="showFactory = false">
        <template slot="title">
          <van-search v-model="factoryFilterText" style="width:70%" placeholder="请输入工序名称" @clear=" factoryFilterText = ''" />
        </template>
      </van-picker>
    </van-popup>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
    <!-- 人员选择 -->
    <van-popup v-model="showUser" position="bottom" :style="{ height: '30%' }">
      <van-picker title="人员选择" show-toolbar :columns="userList" @confirm="onConfirm" @cancel="showUser = false" />
    </van-popup>

    <!-- 不良品登记 -->
    <van-popup v-model="defectiveModel" position="right" :style="{ height: '100%',width:'100%' }">
      <defectiveModel ref="defectiveModel" :defective-model.sync="defectiveModel" @getEntry="getEntryData" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction } from '../../../utils/function'
import qualityControl from './qualityControlPre'
import defectiveModel from './defectiveModel'
export default {
  name: 'FirstInspection',
  components: { qualityControl, defectiveModel },
  data () {
    return {
      activeNames: ['1'], // 表单折叠面板
      defectiveModel: false, // 不良品登记弹出层
      currentDate: new Date(),
      userList: [],
      itemList: [],
      ruleForm: {
        patrolFileList: [],
        itemList: [],
        qualifiedNum: null,
        unqualifiedNum: 0,
        patrolCheckName: JSON.parse(localStorage.getItem('padUserInfo'))?.data.userName, // 检验人
        patrolCheckAt: myFunction(new Date()), // 检验时间
        patrolCheckBy: JSON.parse(localStorage.getItem('padUserInfo'))?.data.userId // 本次检验
      },
      show: false,
      list: [],
      loading: false,
      detailsObj: {},
      showTime: false,
      showUser: false,
      itooles: [],
      checkValList: [],
      result: 1,
      planBatchNo: '', // PC20240812003
      isShowForm: false, // 未发起请求时不展示所有内容
      showProcedure: false, // 工序选择
      procedureList: [],
      procedureFilterText: '',
      showFactory:false, // 工位选择
      factoryList:[],
      factoryFilterText:'',
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler (val) {
        const { qualifiedNum, badNum, scrapNum } = val
        this.ruleForm.patrolCheckNum = Number(qualifiedNum || 0) + Number(badNum || 0) + Number(scrapNum || 0)
      }
    }
  },
  created () {
    const { code } = this.$route.params
    if (code) {
      this.planBatchNo = this.$route.params.code
      this.getDataByPlanBatchNo(code)
    }
  },
  async mounted () {
    /* 获取人员 */
    await this.getUser()
  },
  methods: {
    /**
     * @description: 扫码
     * @param {*} e
     * @return {*}
     */
    scan () {
      this.$router.push('/saomaShow?name=巡检')
    },
    /**
     * @description: 根据工单批次号查询信息
     * @param {*} planBatchNo
     * @return {*}
     */
    async getDataByPlanBatchNo (planBatchNo) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '数据加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      setTimeout(() => {
        toast.clear()
      },500)
      this.isShowForm = false
      const res = await this.$axios.post(`/dobo-product/pro/patrol/check/patrolByBatchNo`,{planBatchNo})
      if (res?.data.code === 200) {
        this.$set(this, 'ruleForm', {
          ...this.ruleForm, ...res.data.data,
          patrolCheckName: JSON.parse(localStorage.getItem('padUserInfo'))?.data.userName,
          patrolCheckBy: JSON.parse(localStorage.getItem('padUserInfo'))?.data.userId,
          patrolCheckAt: myFunction(new Date()), patrolCheckNum: null, qualifiedNum: 0, badNum: 0, scrapNum: 0
        })
        this.procedureList = res.data.data.proFsRouteProcedureList
        this.isShowForm = true
      } else {
        this.isShowForm = false
      }
      // await this.getToolList()
      // await this.getItemList(toast)
    },
    /* 获取所有人员 */
    async getUser () {
      const res = await this.$axios.get('/dobo-user/user/getAllUser')
      if (res.data.code === 200) {
        this.userLists = res.data.data
        res.data.data.forEach(item => {
          this.userList.push(item.name)
        })
      }
    },
    /**
     * @description: 选中工序
     * @return {*}
     */
    selectProcedure (val) {
      const obj = this.procedureList.find(item => item.procedureName === val)
      const { procedureId,procedureCode } = obj
      this.ruleForm = {
        ...this.ruleForm, procedureId, procedureName: val,procedureCode,
        factoryName:null, factoryId:null, equId:null, equName:null, equCode:null
      }
      this.getItem(procedureCode)
      this.getFactoryListByProcedureCode(procedureCode,this.ruleForm.proLineId)
      this.showProcedure = false
    },
    /**
     * @description: 根据工序code 产线id 查询工位
     * @param {*} procedureCode
     * @param {*} proLineId
     * @return {*}
     */
    async getFactoryListByProcedureCode(procedureCode,proLineId){
      const res = await this.$axios.post(`/dobo-product/pro/patrol/check/equipByProcedure`,{
        procedureCode,proLineId
      })
      if(res?.data.code === 200){
        this.factoryList = res.data.data
        if(res.data.data.length >= 1){
          this.selectFactory(res.data.data[0].factoryName)
        }
      }
    },
    /**
     * @description: 选中工位
     * @return {*}
     */
    selectFactory (val) {
      const obj = this.factoryList.find(item => item.factoryName === val)
      const {  factoryName, factoryId, equipId:equId, equipName:equName, equipCode:equCode} = obj
      console.log(obj)
      this.ruleForm = {
        ...this.ruleForm, factoryName, factoryId, equId, equName, equCode
      }
      this.showFactory = false
    },
    /**
     * @description: 根据工序id  工单批次号查询质量控点
     * @param {*} procedureId
     * @return {*}
     */
    async getItem (procedureCode) {
      this.ruleForm.itemList = []
      const res = await this.$axios.post(`/dobo-product/pro/patrol/check/patrolDetail`,{
        planBatchNo:this.planBatchNo,procedureCode
      })
      if (res?.data.code === 200) {
        res.data.data.forEach(item => {
          item.result = 1
        })
        this.ruleForm.itemList = res.data.data
      }
    },
    /* 选择时间 */
    selectTime () {
      this.showTime = true
    },
    /* 时间选择赋值 */
    onTimeChange (value) {
      this.ruleForm.patrolCheckAt = myFunction(value)
      this.showTime = false
    },
    /* 人员选择 */
    onConfirm (e) {
      let id = ''
      this.userLists.forEach(item => {
        if (item.name === e) id = item.id
      })
      this.ruleForm.patrolCheckBy = id
      this.ruleForm.patrolCheckName = e
      this.showUser = false
    },
    /**
     * @description: 获取不良登记信息
     * @param {*} data
     * @return {*}
     */
    getEntryData (data) {
      const badNumList = []
      const scrapNumList = []
      const patrolCheckPoorGradeList = []
      data.forEach((item, index) => {
        if (item.determine === 0) {
          badNumList.push(item.num)
          item.badNum = item.num
        } else {
          scrapNumList.push(item.num)
          item.scrapNum = item.num
        }
        const { determine, num } = item
        item.defectsList.forEach(itx => {
          console.log(index)
          patrolCheckPoorGradeList.push({ ...itx, determine, num, idx: index + 1 })
        })
        // patrolCheckPoorGradeList.push()
      })
      this.ruleForm.badNum = badNumList.length ? this.sum(badNumList) : 0
      this.ruleForm.scrapNum = scrapNumList.length ? this.sum(scrapNumList) : 0
      const { qualifiedNum, badNum, scrapNum } = this.ruleForm
      this.ruleForm.patrolCheckNum = Number(qualifiedNum || 0) + Number(badNum || 0) + Number(scrapNum || 0)
      this.ruleForm.patrolCheckPoorGradeList = patrolCheckPoorGradeList
      console.log(this.ruleForm)
    },
    /**
     * @description: 求和
     * @param {*} arr
     * @return {*}
     */
    sum (arr) {
      return arr.reduce((prev, curr) => Number(prev) + Number(curr), 0)
    },
    /* 获取质量控点 */
    async getItemList (toast) {
      const res = await this.$axios.get(`/dobo-product/pad/patrol/getItemList?bomId=${this.detailsObj.bomId}&materialId=${this.detailsObj.materialId}&procedureCode=${this.detailsObj.procedureCode}&routeId=${this.detailsObj.routeId}`)
      if (res.data.code === 200) {
        if (res.data.data.length < 1) {
          setTimeout(() => {
            toast.clear()
          }, 100)
          this.$dialog.alert({
            title: '提示',
            message: '当前数据没有质量控点请维护质量控点！'
          }).then(() => {
            // this.$router.go(-1)
          })
          return
        } else {
          setTimeout(() => {
            toast.clear()
            this.ruleForm.itemList = res.data.data
          }, 10)
        }
      }
    },
    onOversize (file) {
      this.$toast.fail('文件大小不能超过 5M')
    },
    // 上传图片
    afterRead (items, type) {
      return file => {
        if (file) {
          if (file.constructor === Object) file = [file]
          const toast = this.$toast.loading({
            duration: 0, // 持续展示 toast
            message: '图片上传中...',
            forbidClick: true,
            loadingType: 'spinner'
          })
          file.filter((item, index) => {
            const form = new FormData()
            form.append('file', item.file)
            this.$axios.post('/dobo-file/files-anon', form).then(res => {
              if (res.data.code === 200) {
                item.fileId = res.data.data.id
                item.fileUrl = res.data.data.url
                item.fileName = res.data.data.name
                if (++index === file.length) {
                  toast.clear()
                }
              } else {
                this.$toast.fail(res.data.msg)
                toast.clear()
              }
            })
          })
        }
      }
    },

    submitForm () {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否确认提交？'
        })
        .then(() => {
          console.log(this.ruleForm)
          const { procedureId, itemList, patrolCheckNum } = this.ruleForm
          if (!procedureId) {
            return this.$dialog.alert({ title: '提示', message: '请选择工序' })
          } else if (itemList && itemList.some(item => !item.actualValue && item.actualValue !== 0 && item.isAuto === 0)) {
            return this.$dialog.alert({ title: '提示', message: '检验项存在实测值为空!' })
          } else if (!patrolCheckNum || patrolCheckNum < 1) {
            return this.$dialog.alert({ title: '提示', message: '检验数不能小于1,请维护合格、不良品、废品数！' })
          } else {
            this.submitApi()
          }
        })
        .catch(() => {
          return false
        })
    },
    submitApi () {
      // const toast = this.$toast.loading({
      //   duration: 0, // 持续展示 toast
      //   message: '提交中...',
      //   forbidClick: true,
      //   loadingType: 'spinner'
      // })
      const params = Object.assign({}, this.ruleForm)
      delete params.proFsRouteProcedureList
      params.itemList.forEach(item => {
        item.itemFileList.forEach(itx => delete itx.content)
      })

      params.fileList.forEach(item => delete item.content)
      console.log(params)
      this.$axios.post('/dobo-product/pro/patrol/check/patrolSave', params).then(res => {
        if (res.data.code === 200) {
          // toast.clear()
          this.$dialog
            .alert({
              title: '提示',
              message: '提交成功!'
            })
            .then(() => {
              // this.$router.push('/PatrolInspection')
              window.location.reload()
            })
            .catch(() => { })
        } else {
          this.$toast.fail(res.data.msg)
          setTimeout(() => {
            // toast.clear()
            // this.$router.push('/PatrolInspection')
            window.location.reload()
          }, 1000)
        }
      })
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/task')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .publicBox {
    .vanForm {
      .van-field {
        border-bottom: 1px solid #ebedf0;
      }
      .zhedie {
        height: 45px;
        line-height: 45px;
        background: green;
        width: 100%;
        text-align: center;
      }
    }
  }
  .qualityContent {
    height: calc(100% - 360px);
    overflow: hidden;
    h1 {
      height: 40px;
      line-height: 40px;
      font-weight: normal;
      text-align: center;
      background: #022566;
      color: #fff;
    }
    .contentItem {
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
}
</style>
<style lang='scss'>
</style>
